<template>
  <div class="table-example">
    <h2>表格示例</h2>
    
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>基础表格</span>
          <div class="header-operations">
            <el-input
              v-model="searchText"
              placeholder="输入关键字搜索"
              class="search-input"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">添加数据</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="filteredTableData"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="name" label="姓名" sortable />
        <el-table-column prop="age" label="年龄" sortable width="100" />
        <el-table-column prop="gender" label="性别" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.gender === '男' ? 'primary' : 'success'">
              {{ scope.row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="1" :max="120" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option label="活跃" value="活跃" />
            <el-option label="禁用" value="禁用" />
            <el-option label="锁定" value="锁定" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '张三',
    age: 28,
    gender: '男',
    address: '北京市朝阳区某小区A栋101室',
    status: '活跃'
  },
  {
    id: 2,
    name: '李四',
    age: 32,
    gender: '男',
    address: '上海市浦东新区某花园B栋202室',
    status: '活跃'
  },
  {
    id: 3,
    name: '王五',
    age: 24,
    gender: '男',
    address: '广州市天河区某大厦C座303室',
    status: '锁定'
  },
  {
    id: 4,
    name: '赵六',
    age: 35,
    gender: '男',
    address: '深圳市南山区某公寓D栋404室',
    status: '活跃'
  },
  {
    id: 5,
    name: '钱七',
    age: 29,
    gender: '女',
    address: '成都市武侯区某小区E栋505室',
    status: '禁用'
  },
  {
    id: 6,
    name: '孙八',
    age: 26,
    gender: '女',
    address: '杭州市西湖区某花园F栋606室',
    status: '活跃'
  },
  {
    id: 7,
    name: '周九',
    age: 31,
    gender: '男',
    address: '南京市玄武区某大厦G座707室',
    status: '活跃'
  },
  {
    id: 8,
    name: '吴十',
    age: 27,
    gender: '女',
    address: '武汉市江汉区某公寓H栋808室',
    status: '锁定'
  }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(8)

// 搜索相关
const searchText = ref('')

// 选中的行
const multipleSelection = ref([])

// 过滤后的表格数据
const filteredTableData = computed(() => {
  if (!searchText.value) {
    return tableData.value
  }
  
  return tableData.value.filter(data => {
    return Object.keys(data).some(key => {
      // 排除id字段
      if (key === 'id') return false
      
      const value = data[key]
      if (typeof value === 'string') {
        return value.toLowerCase().includes(searchText.value.toLowerCase())
      } else if (typeof value === 'number') {
        return value.toString().includes(searchText.value)
      }
      return false
    })
  })
})

// 弹窗表单相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const formRef = ref(null)

const form = reactive({
  id: null,
  name: '',
  age: 18,
  gender: '男',
  address: '',
  status: '活跃'
})

const formRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 根据状态返回标签类型
const statusTagType = (status) => {
  switch (status) {
    case '活跃':
      return 'success'
    case '禁用':
      return 'danger'
    case '锁定':
      return 'warning'
    default:
      return 'info'
  }
}

// 处理搜索
const handleSearch = () => {
  // 重置分页到第一页
  currentPage.value = 1
}

// 处理选择变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 处理查看
const handleView = (row) => {
  ElMessage({
    message: `查看用户: ${row.name}，ID: ${row.id}`,
    type: 'info'
  })
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 模拟删除操作
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      totalItems.value--
      ElMessage({
        type: 'success',
        message: '删除成功!',
      })
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  })
}

// 处理添加
const handleAdd = () => {
  dialogType.value = 'add'
  formRef.value?.resetFields()
  
  // 初始化form
  Object.assign(form, {
    id: Date.now(),
    name: '',
    age: 18,
    gender: '男',
    address: '',
    status: '活跃'
  })
  
  dialogVisible.value = true
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      // 添加操作
      tableData.value.unshift({...form})
      totalItems.value++
      ElMessage.success('添加成功!')
    } else {
      // 编辑操作
      const index = tableData.value.findIndex(item => item.id === form.id)
      if (index > -1) {
        tableData.value[index] = {...form}
        ElMessage.success('更新成功!')
      }
    }
    
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请检查表单填写是否正确')
  }
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  console.log(`每页 ${val} 条`)
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  console.log(`当前页: ${val}`)
}
</script>

<style scoped>
.table-example {
  padding: 20px;
}

.table-card {
  margin-top: 20px;
  margin-bottom: 40px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 